<template>
  <basic-container>
    <el-row :gutter="20">
      <el-col :span="11">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="标签生成">
            <avue-form id="rawMaterialForm" class="newFormStyle" ref="rawMaterialForm" v-model="rawMaterialForm" :option="rawMaterialOption" @submit="rawMaterialLabelGenerate">
              <template slot-scope="{}" slot="minPackingQuantityLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>最小包装数量:</span>
              </template>
            </avue-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="13">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="标签打印">
            <div class="sequenceInfo">
              <el-row>
                <el-col :span="15">
                  <print-template ref="printInfo" :url="url" templateType="MATERIAL" @getPrintInfo="getPrintInfo"></print-template>
                  <div style="display: flex; justify-content: flex-end">
                    <el-button type="primary" size="small" icon="el-icon-printer" @click="printTest">打印测试</el-button>
                    <el-button type="primary" size="small" icon="el-icon-printer" @click="batchPrinting">打印标签</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane label="标签记录">
        <avue-crud
          :defaults.sync="recordDefaults"
          class="serialNoGenerationRecord"
          ref="serialNoGenerationRecord"
          :table-loading="loading"
          :option="serialNoGenerationRecordOption"
          :data="serialnoData"
          @row-click="serialnoRowClick"
          @selection-change="selectionChange"
        >
          <template slot-scope="{ row }" slot="menu">
            <el-button icon="el-icon-printer" size="small" type="text" @click="Reprint(row)" :disabled="row.isPrinted !== 1 || ['REVORK', 'SCRAP'].includes(row.generationType)">
              <span>重打</span>
            </el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>
    <!-- 操作日志 -->
    <operation-log ref="operationLog"></operation-log>
    <!-- 选择收料记录组件 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body title="序列号规则时间修改" :visible.sync="timeConfigModel" width="30%">
      <avue-form ref="timeConfigForm" v-model="timeConfig" :option="timeConfigOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSaveTimeConfig"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="timeConfigModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body title="重打" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <div style="display: flex; justify-content: center; margin-bottom: 10px">
        <span style="color: red">注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>重打</span></el-button>
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <print-time-input-form :visible.sync="printDialog" :other-info-option="otherInfoOption" @printInfo="(otherInfo) => handlePrintSequence(otherInfo)"></print-time-input-form>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import printTemplate from '@/views/product/components/printTemplate';
import { getSeqNoRules } from '@/util/global';
import { getYearWeek, showSuccessLog, showFailLog } from '@/util/helpers';
import { createSequence, getSourceList, packPrint, printTest, historycreate, historyPrint } from '@/api/labelManagement/inventoryPartLabelPrint.js';
import { getDetail as getSequencedefinitionDetail } from '@/api/admin/sequencedefinition';
import OperationLog from '@/components/operation-log/operation-log.vue';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
import { getYearAndWeek, getMondayOfWeek } from '@/util/helpers';
import { getPrintFormMixin } from '@/mixins/getPrintFormMixin';
import { getPrintHistory } from '@/api/admin/barcode-record';
import printTimeInputForm from '@/components/print-time-input-form';
export default {
  components: {
    CommonModalTemplate,
    printTemplate,
    OperationLog,
    printTimeInputForm
  },
  mixins: [getPrintFormMixin],
  data() {
    return {
      url: '/api/mes-admin/labeltemplate/page?type=material&status=1',
      rawMaterialForm: {}, //原料标签-采购单表单信息
      rawMaterialOption: {
        //原料标签-采购单表单配置
        labelPosition: 'right',
        labelWidth: 128,
        labelHeight: 80,
        // menuBtn: true,
        submitBtn: true,
        submitText: '生成标签',
        emptyBtn: false,
        menuPosition: 'right',
        column: [
          {
            label: '历史物料',
            prop: 'partMasterName',
            type: 'search',
            span: 12,
            placeholder: '请选择 历史物料',
            disabled: true,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            appendClick: () => {
              this.openPartCommonModal();
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 12,
            disabled: true,
            placeholder: '物料编码'
          },
          {
            label: '物料名称',
            prop: 'partMasterName',
            span: 12,
            disabled: true,
            placeholder: '物料名称'
          },
          {
            label: '供应商编码',
            prop: 'vendorCode',
            span: 12,
            disabled: true,
            placeholder: '供应商编码'
          },
          {
            label: '供应商名称',
            prop: 'partnerName',
            span: 12,
            disabled: true,
            placeholder: '供应商名称'
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo',
            span: 12,
            disabled: true,
            placeholder: '供应商批次'
          },
          {
            label: '物料数量',
            prop: 'packQuantitySpec',
            span: 12,
            disabled: true,
            placeholder: '物料数量'
          },
          {
            label: '可打印数量',
            prop: 'quantity',
            span: 12,
            disabled: true,
            placeholder: '可打印数量'
          },
          {
            label: '生产日期',
            prop: 'vendorDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            span: 12,
            disabled: true,
            placeholder: '请选择 生产日期'
            // rules: [
            //   {
            //     required: true,
            //     trigger: 'submit',
            //     validator: (rule, value, callback) => {
            //       callback();
            //     }
            //   }
            // ]
            // change: ({ column, value }) => {
            //   this.rawMaterialForm.week = value ? getYearAndWeek(value) : '';
            // }
          },
          {
            label: '周号',
            prop: 'week',
            disabled: true
            // enter: (value) => {
            //   if (value.length !== 4) {
            //     this.$message.warning('请输入正确的周号!');
            //   } else {
            //     this.rawMaterialForm.vendorDate = getMondayOfWeek(value);
            //   }
            // }
          },
          {
            label: 'D/C',
            prop: 'lotNo'
          },
          {
            label: '品牌',
            prop: 'materialBrand'
          },
          {
            label: '检验批次',
            prop: 'inspectionLotNo'
          },
          {
            label: '最小包装数量',
            prop: 'minPackingQuantity',
            span: 12,
            rules: [
              {
                required: true,
                message: '请输入最小包装数量',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^\+?[1-9]\d*$/;
                  if (!reg.test(value)) {
                    callback(new Error('请输入正整数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },

          {
            label: '序列号规则',
            prop: 'sequenceName',
            type: 'search',
            placeholder: '请选择 序列号规则',
            span: 12,
            disabled: true,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            appendClick: () => {
              this.openSerialnoCommonModal();
            }
          },
          {
            label: '本次生成数量',
            prop: 'produceQuantity',
            placeholder: '请输入本次生产数量',

            rules: [
              {
                required: true,
                message: '请输入本次生产数量',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^\+?[1-9]\d*$/;
                  if (!reg.test(value)) {
                    callback(new Error('请输入正整数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            span: 12
          }
        ]
      },
      timer: new Date().getTime(),
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      sequenceRuleInfo: {}, //产品序列号规则信息
      recordDefaults: {},
      serialNoGenerationRecordOption: {
        //工单产品序列号内容配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        menu: true,
        highlightCurrentRow: true,
        column: [
          {
            label: '起始包装条码',
            prop: 'sequenceNumberFrom'
          },
          {
            label: '结尾包装条码',
            prop: 'sequenceNumberTo'
          },
          {
            label: '序列号总数',
            prop: 'quantity'
          },
          {
            label: 'MPQ',
            prop: 'packingQuantity'
          },
          {
            label: '状态',
            prop: 'isPrinted',
            html: true,
            formatter: (val) => {
              switch (val.isPrinted) {
                case 0:
                  return `<span class="text-yellow">未打印</span>`;
                case 1:
                  return `<span class="text-green">已打印</span>`;
                case 2:
                  return `<span class="text-red">部分打印</span>`;
                default:
                  return `<span class="text-red">报废</span>`;
                  break;
              }
            }
          },
          {
            label: '生成时间',
            prop: 'createTime'
          },
          {
            label: '生成类型',
            prop: 'generationType',
            html: true,
            formatter: (val) => {
              switch (val.generationType) {
                case 'NORMAL':
                  return '正常';
                case 'SCRAP':
                  return '报废';
                case 'APPEND':
                  return '增补';
                case 'REPLACE':
                  return '置换';
                case 'REVORK':
                  return '撤销';
                default:
                  break;
              }
            }
          }
        ]
      },
      serialnoData: [], //序列号生成记录
      timeConfigModel: false, //序列号规则时间修改模态框是否显示
      timeConfig: {}, //序列号规则时间配置
      timeConfigOption: {
        //序列号规则时间修改内容配置
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '年代码',
            prop: 'year',
            type: 'year',
            format: 'yyyy',
            valueFormat: 'yyyy',
            span: 20,
            display: false
          },
          {
            label: '月代码',
            prop: 'month',
            type: 'month',
            format: 'MM',
            valueFormat: 'MM',
            span: 20,
            display: false
          },
          {
            label: '周代码',
            prop: 'week',
            span: 20,
            display: false
          },
          {
            label: '日代码',
            prop: 'day',
            type: 'date',
            format: 'dd',
            valueFormat: 'dd',
            span: 20,
            display: false,
            change(val) {
              console.log(val, Date.parse(val), Object.prototype.toString.call(Date.parse(val)));
            }
          }
        ]
      },
      printInfo: {}, //打印机打印模版信息
      defaults: {},
      printInfoModel: false,
      printInfo: {},
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '起始流水号',
            prop: 'sequenceNumberFrom',
            span: 20
          },
          {
            label: '结束流水号',
            prop: 'sequenceNumberTo',
            span: 20
          },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      selectionList: [],
      packingList: {}
    };
  },
  mounted() {
    this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
    this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
    this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
    this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开选择物料模态框
     */
    openPartCommonModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择历史物料（双击进行选择）',
        url: '/api/mes-warehouse/packing/page?packSubType=HISTORY_MATERIAL',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',

            search: true
          },
          {
            label: '物料名称',
            prop: 'partMasterName',
            search: true
          },
          {
            label: '供应商名称',
            prop: 'partnerName'
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          {
            label: '仓库',
            prop: 'inventoryName'
          },
          {
            label: '储位',
            prop: 'areaName'
          },
          {
            label: '生产日期',
            prop: 'vendorDate'
          },
          {
            label: '物料数量',
            prop: 'packQuantitySpec'
          }
        ]
      };
    },

    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partModal':
          this.packingList = rowData;
          this.rawMaterialForm.partMasterId = this._get(rowData, 'id', '');
          this.rawMaterialForm.partNo = this._get(rowData, 'partNo', '');
          this.rawMaterialForm.partMasterName = this._get(rowData, 'partMasterName', '');
          this.rawMaterialForm.vendorCode = this._get(rowData, 'vendorCode', '');
          this.rawMaterialForm.partnerName = this._get(rowData, 'partnerName', '');
          this.rawMaterialForm.vendorLotNo = this._get(rowData, 'vendorLotNo', '');
          this.rawMaterialForm.vendorDate = this._get(rowData, 'vendorDate', '');
          this.rawMaterialForm.packQuantitySpec = this._get(rowData, 'packQuantitySpec', '');
          this.rawMaterialForm.quantity = this._get(rowData, 'quantity', '');
          let date = this._get(rowData, 'vendorDate', '');
          this.rawMaterialForm.week = getYearAndWeek(date.split(' ')[0]) || '';
          // 带出来的
          this.rawMaterialForm.minPackingQuantity = this._get(rowData, 'minPackingQuantity', '');
          const labelTemplateId = this._get(rowData, 'labelTemplateId', '');
          const labelTemplateName = this._get(rowData, 'labelTemplateName', '');
          this.$refs.printInfo.setPrintLabel(labelTemplateId, labelTemplateName);
          this.printInfo.labelTemplateId = labelTemplateId;

          this.rawMaterialForm.inspectionLotNo = this._get(rowData, 'inspectionLotNo', '');
          this.rawMaterialForm.lotNo = this._get(rowData, 'lotNo', '');
          this.rawMaterialForm.materialBrand = this._get(rowData, 'materialBrand', '');
          this.getSequenceRecordById(this.rawMaterialForm.partMasterId);
          break;
        case 'serialnoModal':
          this.rawMaterialForm.sequenceName = this._get(rowData, 'name', '');
          this.rawMaterialForm.sequenceDefinitionId = this._get(rowData, 'id', '');
          break;
        case 'printersModal':
          this.printInfo.equipmentId = this._get(rowData, 'id', '');
          this.printInfo.equipmentName = this._get(rowData, 'name', '');
          break;
        case 'labelTemplateModal':
          this.printInfo.labelTemplateId = this._get(rowData, 'id', '');
          this.printInfo.labelTemplateName = this._get(rowData, 'fileName', '');
          break;
        default:
          break;
      }
    },

    /**
     * 生成序列号行点击
     */
    serialnoRowClick(row) {
      this.$refs.serialNoGenerationRecord.toggleSelection(row);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=material&subType=raw_material_packaging',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '进制符',
            prop: 'hexString'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },

    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
        const dataId = printInfo.dataId;
        if (dataId) {
          this.getDetail(printInfo.dataId);
        } else {
          this.fieldList = [];
        }
      }
    },
    /**
     * 原料标签-采购单生成
     */
    rawMaterialLabelGenerate(row, done) {
      if (!row.minPackingQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入最小包装数量!'
        });
        done();
        return;
      }
      // console.log(reg.test(Number(row.minPackingQuantity)));
      const reg2 = /^[1-9]\d*$/g;
      if (!reg2.test(Number(row.minPackingQuantity))) {
        this.$message({
          type: 'warning',
          message: '最小包装数量为正整数!'
        });
        done();
        return;
      }

      if (!row.sequenceDefinitionId) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      this.rawMaterialForm['timeConfig'] = this.timeConfig;
      this.rawMaterialForm['type'] = 'RECEIVING_SUBMIT';
      let params = {
        actCode: 'other-receive-gen-pack-activity',
        requestParams: this.rawMaterialForm
      };

      let paramsMap = {
        transactionType: 'UNPACKING',
        packingList: [this.packingList],
        minPackingQuantity: this.rawMaterialForm.minPackingQuantity,
        quantity: this.rawMaterialForm.produceQuantity,
        produceQuantity: this.rawMaterialForm.produceQuantity,
        lotNo: this.rawMaterialForm.lotNo,
        materialBrand: this.rawMaterialForm.materialBrand,
        week: this.rawMaterialForm.week,
        inspectionLotNo: this.rawMaterialForm.inspectionLotNo,
        sequenceDefinitionId: this.rawMaterialForm.sequenceDefinitionId,

        equipmentId: this.printInfo.printerId,
        labelTemplateId: this.printInfo.labelTemplateId
      };
      historycreate(paramsMap).then(
        (res) => {
          this.getSequenceRecordById(this.rawMaterialForm.partMasterId);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.rawMaterialForm.receivedQuantity = '';
          this.rawMaterialForm.minPackingQuantity = '';
          this.rawMaterialForm.remark = '';
          showSuccessLog(res.data.msg);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 根据id获取所有生成记录
     */
    getSequenceRecordById(id) {
      let params = {
        sourceId: id
      };
      getSourceList(params).then(
        (res) => {
          this.serialnoData = this._get(res, 'data.data', []);
          if (this.serialnoData.length > 0 && this.serialnoData[0].isPrinted === 0) {
            this.serialnoRowClick(this.serialnoData[0]);
          }
        },
        (error) => {
          this.serialnoData = [];
        }
      );
    },
    //解析
    handleAnalysis() {
      const regex = /\[(.*?)\]/g;
      const tempSequenceNoFormat = this.sequenceRuleInfo.sequenceNoFormat.toLowerCase().match(regex);
      const sequenceNoFormat = tempSequenceNoFormat.map((match) => match.slice(1, -1));
      const sequenceNoFormatZh = this.sequenceRuleInfo.sequenceNoFormatZh.split('+');
      const length = this.saleReturnKey.length;
      const column = [];
      const key = []; //存储分析出来的label的key
      sequenceNoFormat.forEach((item, index) => {
        if (item !== 's') {
          key.push(item);
          column.push({
            label: sequenceNoFormatZh[index],
            prop: item,
            span: 12,
            tip: sequenceNoFormatZh[index],
            tipPlacement: 'top'
          });
        }
      });
      this.saleReturnKey = key;
      // 防止单个条码一直解析
      if (this.saleOrderReturnOption.column.length < this.saleReturnKey.length + 8) {
        this.saleOrderReturnOption.column.splice(7, 0, ...column);
      }
    },
    handleSelect(val) {
      this.saleOrderReturnForm.quantity = this.saleReturnList.find((item) => item.partMasterId === val).quantity || 0;
    },
    async getSaleReturnList(params) {
      try {
        this.saleReturnLoading = true;
        const res = await getSalesReturnList(params);
        this.saleReturnList = res.data.data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.saleReturnLoading = false;
      }
    },
    /**
     * 打印测试
     */
    printTest() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      if (this.serialnoData.length === 0) {
        this.$message.warning('请先生成标签记录！');
        return;
      }
      let params = {
        equipmentId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId,
        sequenceNumber: this.serialnoData[0].sequenceNumberFrom
      };
      printTest(params).then(
        (res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          this.getSequenceRecordById(this.rawMaterialForm.partMasterId);
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    /**
     * 标签打印
     */
    batchPrinting() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择标签记录！');
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning('请选择未打印的记录！');
        return;
      }
      if (!this.fieldList.length) {
        this.handlePrintSequence();
      } else {
        // 当标签模版绑定了数据源且设置了数据 打开其他信息弹窗
        this.printDialog = true;
      }
    },
    handlePrintSequence(otherInfo = {}) {
      try {
        let list = [];
        this._forEach(this.selectionList, (item) => {
          list.push(item.id);
        });
        let params = {
          equipmentId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          sequenceGenerationIdList: list
        };
        if (Object.keys(otherInfo).length) {
          params.printInput = JSON.stringify(otherInfo);
        }
        historyPrint(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.rawMaterialForm.partMasterId);
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      } catch (e) {
        console.log(e);
      }
    },
    async Reprint(row) {
      this.printInfo.sequenceNumberFrom = row.sequenceNumberFrom;
      this.printInfo.sequenceNumberTo = row.sequenceNumberTo;
      this.printInfo.generationId = row.id;
      try {
        const res = await getPrintHistory(row.id);
        const data = res.data.data;
        this.printInfo.labelTemplateName = data.labelTemplateName;
        this.printInfo.equipmentName = data.equipmentName;
        this.printInfo.equipmentId = data.equipmentId;
        this.printInfo.labelTemplateId = data.labelTemplateId;
      } catch (e) {
        console.log(e);
      }
      this.printInfoModel = true;
      // this.printInfo = row;
    },
    /**
     * 打印
     */
    printSubmit() {
      this.$refs.printForm.validate((valid, done) => {
        this.printInfo.fromSequenceNumber = this._cloneDeep(this.printInfo.sequenceNumberFrom);
        this.printInfo.toSequenceNumber = this._cloneDeep(this.printInfo.sequenceNumberTo);
        let params = {
          fromSequenceNumber: this.printInfo.fromSequenceNumber,
          toSequenceNumber: this.printInfo.toSequenceNumber,
          generationId: this.printInfo.generationId,
          labelTemplateId: this.printInfo.labelTemplateId,
          equipmentId: this.printInfo.equipmentId
        };
        if (valid) {
          packPrint(params).then(
            (res) => {
              this.$refs.printForm.resetFields();
              this.printInfoModel = false;
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.getSequenceRecordById(this.rawMaterialForm.partMasterId);
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?type=material&status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.sequenceInfo {
  table {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    font-size: 14px;
    th {
      border: 1px solid #ebeef5;
      background: #fafafa;
      height: 30px;
    }
    tr {
      border: 1px solid #ebeef5;
    }
    td {
      border: 1px solid #ebeef5;
      height: auto;
      text-align: center;
    }
    p {
      margin-left: 30px;
    }
  }
}
.newFormStyle {
  ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 15px;
  }
  ::v-deep .el-input--small input {
    height: 30px;
    line-height: 30px;
  }
}
.generateSerialNoInfo {
  div {
    margin: 5px 10px;
  }
}
.printButton {
  text-align: right;
}
::v-deep .el-button--primary {
  background-color: #5badc4;
  color: #ffffff;
}
// ::v-deep .el-form-item__error {
//   display: contents;
// }
.sale_order_return {
  ::v-deep .el-form-item__label {
    white-space: nowrap; /* 禁止换行 */
    overflow: hidden;
    text-overflow: ellipsis; /* 超出部分显示省略号 */
  }
}
.informationLabel {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
</style>
